<template>
  <div class="page">
    <section class="page__content" v-if="designerData">
      <Process ref="processDesign"  :conf="designerData"  @startNodeChange="onStartChange"/>
    </section>
    <div class="publish">
      <el-button size="small" type="primary" @click="previewJson"><i class="el-icon-view"></i>预览JSON</el-button>
      <el-button size="small" type="primary" @click="previewXml"><i class="el-icon-view"></i>预览XML</el-button>
      <el-button size="small" type="primary" @click="previewBpmn"><i class="el-icon-view"></i>bpmn预览</el-button>
      <el-button size="small" type="primary" @click="save"><i class="el-icon-s-claim"></i>保存</el-button>
      <el-button size="small" type="primary" @click="publish"><i class="el-icon-s-promotion"></i>发布</el-button>
    </div>
    <el-dialog title="预览" width="60%" v-model="previewModelVisible" append-to-body destroy-on-close>
      <highlightjs :language="previewType" :code="previewResult" style="height: 70vh" />
    </el-dialog>
    <!-- Bpmn流程图 -->
    <el-dialog :title="processView.title" v-model="processView.open" width="70%" append-to-body destroy-on-close>
      <process-viewer :key="`designer-${processView.title}`" :xml="processView.xmlData" :style="{height: '400px'}" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onBeforeMount, onBeforeUnmount, computed, onMounted, defineExpose } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { dingdingToBpmn } from '@/api/workflow/process';
import Process from "./components/Process";
import ProcessDesigner from '@/components/ProcessDesigner';
import ProcessViewer from '@/components/ProcessViewer';
import { vuePlugin } from '@/plugins/package/highlight';
import 'highlight.js/styles/atom-one-dark-reasonable.css';
import convert from "xml-js";
import { propTypes } from '@/utils/propTypes';

// 使用vuePlugin
// import { useHighlight } from '@/plugins/package/highlight';

// const designerData = ref<{ bpmnXml?: string; form?: any; loading?: boolean; title?: string } | null>(null);

const props = defineProps({
  designerData: {
    type: Object,
    required: true
  }
});

const previewModelVisible = ref(false);
const activeStep = ref<string>("processDesign");
const previewResult = ref<string>("");
const previewType = ref<string>("xml");
const processView = ref<{ title: string; open: boolean; xmlData: string }>({
  title: '',
  open: false,
  xmlData: "",
});
const steps = ref<{ label: string; key: string }[]>([
  { label: "流程设计", key: "processDesign" }
]);

const processDesign = ref();
// const processDesign = ref<ElFormInstance>();

const beforeUnload = (e: BeforeUnloadEvent) => {
  const confirmationMessage = '离开网站可能会丢失您编辑得内容';
  e.returnValue = confirmationMessage; // 标准用法
  return confirmationMessage; // 一些旧版浏览器
}

onBeforeMount(() => {
  window.addEventListener('beforeunload', beforeUnload);
});

onBeforeUnmount(() => {
  window.removeEventListener('beforeunload', beforeUnload);
});

const translateX = computed(() => {
  return `translateX(${steps.value.findIndex(t => t.key === activeStep.value) * 100}%)`;
});

const previewJson = async () => {
  // const getCmpData = (name) => { return  this.$refs[name].getData() }
  // processDesign 返回的是Promise 因为要做校验
  // console.log("publish getCmpData",getCmpData)
  // const p3 = getCmpData('processDesign')

  const p3 = processDesign.value.getData()
  Promise.all([p3])
    .then(res => {
      const param = {
        processData: res[0].formData
      }
      previewResult.value = JSON.stringify(param, null, 2);//json格式化
      previewType.value = "json";
      previewModelVisible.value = true;
    })
    .catch(err => {
      // err.target && (this.activeStep = err.target)
      // err.msg && this.$message.warning(err.msg)
    })

  // try {
  //   const data = await processDesign.value?.getData();
  //   previewResult.value = JSON.stringify(data.formData, null, 2); // json格式化
  //   previewType.value = "json";
  //   previewModelVisible.value = true;
  // } catch (err: any) {
  //   if (err.target) activeStep.value = err.target;
  //   if (err.msg) ElMessage.warning(err.msg);
  // }
};

const previewXml = async () => {
  try {
    const data = await processDesign.value?.getData();
    const param = { processData: data.formData };
    const json = JSON.stringify(param, null, 2); // json格式化
    const res = await dingdingToBpmn(json);
    if (res.code === 200) {
      previewResult.value = res.msg;
      previewType.value = "xml";
      previewModelVisible.value = true;
    }
  } catch (err: any) {
    if (err.target) activeStep.value = err.target;
    if (err.msg) ElMessage.warning(err.msg);
  }
};

const previewBpmn = async () => {
  try {
    const data = await processDesign.value?.getData();
    const param = { processData: data.formData };
    const json = JSON.stringify(param, null, 2); // json格式化
    const res = await dingdingToBpmn(json);
    if (res.code === 200) {
      processView.value.title = "Bpmn流程图预览";
      processView.value.xmlData = res.msg;
    }
    processView.value.open = true;
  } catch (err: any) {
    if (err.target) activeStep.value = err.target;
    if (err.msg) ElMessage.warning(err.msg);
  }
};

const publish = async () => {
  try {
    const data = await processDesign.value?.getData();
    const param = { processData: data.formData };
    sendToServer(param);
  } catch (err: any) {
    if (err.target) activeStep.value = err.target;
    if (err.msg) ElMessage.warning(err.msg);
  }
};

const save = async () => {
  try {
    const data = await processDesign.value?.getData();
    const flowData = { processData: data.formData };
    emit('save', flowData);
  } catch (err: any) {
    if (err.target) activeStep.value = err.target;
    if (err.msg) ElMessage.warning(err.msg);
  }
};

const exit = () => {
  ElMessageBox.confirm('离开此页面您得修改将会丢失, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage({
      type: 'success',
      message: '模拟返回!'
    });
  }).catch(() => { });
};

const onInitiatorChange = (val, labels: string) => {
  let startNode = processDesign.value?.data;
  startNode.properties.initiator = val['dep&user'];
  startNode.content = labels || '所有人';
  processDesign.value?.forceUpdate();
};

const onStartChange = (node: any) => {
  // 同步到基础设置发起人数据
  // const basicSetting = ref<InstanceType<typeof BasicSetting> | null>(null);
  // basicSetting.value?.formData.initiator = { 'dep&user': node.properties.initiator };
};

// 暴露方法
defineExpose({
  previewJson,
  previewXml,
  previewBpmn,
  publish,
  save,
  exit,
  onInitiatorChange,
  onStartChange
});

const sendToServer = (param: { processData: any }) => {
  ElMessage({
    title: '数据已整合完成',
    message: '请在预览中查看数据输出',
    position: 'bottom-right'
  });
};
</script>

<style lang="scss" scoped>
.publish {
    position: absolute;
    top: 15px;
    right: 80px;
    z-index: 1000;

    i {
      margin-right: 6px;
    }

    button {
      border-radius: 15px;
    }
  }

</style>

